package utils;

import burp.api.montoya.http.message.responses.HttpResponse;
import ui.RulePanel;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeoutException;
import java.util.regex.PatternSyntaxException;

import static utils.PermissionTestUtil.evaluateTestResult;

public class RuleUtil {

    /**
     * 根据配置规则判断测试结果
     *
     * @param originalResponse 原始响应
     * @param testResponse 测试响应
     * @param rules 规则列表
     * @param logicRelation 逻辑关系（AND/OR）
     * @return 测试结果枚举
     */
    public static PermissionTestUtil.TestResult evaluateTestResultWithRules(
            HttpResponse originalResponse,
            HttpResponse testResponse,
            List<RulePanel.Rule> rules,
            String logicRelation) {

        if (originalResponse == null || testResponse == null) {
            return PermissionTestUtil.TestResult.POTENTIALLY_BYPASSED;
        }

        // 如果没有规则，则使用默认判断逻辑
        if (rules == null || rules.isEmpty()) {
            return evaluateTestResult(originalResponse, testResponse);
        }

        boolean allRulesMatched = true;
        boolean anyRuleMatched = false;

        for (RulePanel.Rule rule : rules) {
            boolean ruleMatched = evaluateRule(testResponse, rule);

            if ("And".equalsIgnoreCase(logicRelation)) {
                if (!ruleMatched) {
                    allRulesMatched = false;
                    break;
                }
            } else { // Or logic
                if (ruleMatched) {
                    anyRuleMatched = true;
                }
            }
        }

        boolean rulesMatched = "And".equalsIgnoreCase(logicRelation) ? allRulesMatched : anyRuleMatched;

        if (rulesMatched) {
            // 规则匹配成功，说明可防御
            return PermissionTestUtil.TestResult.DEFENDED;
        } else {
            // 规则匹配失败，需要进一步判断
            String originalBody = originalResponse.bodyToString();
            String testBody = testResponse.bodyToString();

            if (Objects.equals(originalBody, testBody)) {
                // 响应体与原始请求相同，说明被绕过
                return PermissionTestUtil.TestResult.BYPASSED;
            } else {
                // 响应与原始请求内容不同，待确定
                return PermissionTestUtil.TestResult.POTENTIALLY_BYPASSED;
            }
        }
    }

    /**
     * 评估单个规则是否匹配
     *
     * @param response 响应对象
     * @param rule 规则
     * @return 是否匹配
     */
    private static boolean evaluateRule(HttpResponse response, RulePanel.Rule rule) {
        String ruleType = rule.getType();
        String ruleContent = rule.getContent();

        try {
            if ("状态码等于（数字）".equals(ruleType)) {
                int statusCode = response.statusCode();
                return Integer.toString(statusCode).equals(ruleContent.trim());
            } else if ("状态码不等于（数字）".equals(ruleType)) {
                int statusCode = response.statusCode();
                return !Integer.toString(statusCode).equals(ruleContent.trim());
            } else if ("响应体包含（字符串）".equals(ruleType)) {
                String body = response.bodyToString();
                return body.contains(ruleContent);
            } else if ("响应体不包含（字符串）".equals(ruleType)) {
                String body = response.bodyToString();
                return !body.contains(ruleContent);
            } else if ("响应体包含（正则）".equals(ruleType)) {
                String body = response.bodyToString();
                return RegexUtil.safeRegexMatch(ruleContent, body);
            } else if ("响应体不包含（正则）".equals(ruleType)) {
                String body = response.bodyToString();
                return !RegexUtil.safeRegexMatch(ruleContent, body);
            }
        } catch (PatternSyntaxException e) {
            // 正则表达式语法错误
            return false;
        } catch (NumberFormatException e) {
            // 数字格式错误
            return false;
        } catch (TimeoutException e) {
            // 正则表达式匹配超时
            System.err.println("Regex matching timeout for pattern: " + ruleContent);
            return false;
        } catch (Exception e) {
            // 其他异常
            return false;
        }

        // 未知规则类型
        return false;
    }

    /**
     * 关闭正则表达式执行器
     */
    public static void shutdownRegexExecutor() {
        RegexUtil.shutdownRegexExecutor();
    }
}
